<template>
  <l-layout class="l-tab-page apicode" :topMove="false" :bottomMove="false">
    <template #top>
      <l-panel style="padding-bottom: 0">
        <div class="title">接口生成</div>
        <div class="steps">
          <el-steps :active="stepActive" simple finish-status="success">
            <el-step :title="$t('信息配置')"></el-step>
            <el-step :title="$t('代码预览')"></el-step>
          </el-steps>
        </div>
      </l-panel>
    </template>

    <l-layout v-show="steps(0)" :left="800">
      <template #left>
        <l-panel style="padding: 0; padding-left: 8px">
          <div class="base-form-wraper">
            <el-form :model="formData" :rules="rules" size="mini" ref="baseInfo" label-width="80px">
              <el-col :span="24">
                <el-form-item label="功能名称" prop="name">
                  <el-input v-model="formData.name"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="功能描述" prop="des">
                  <el-input v-model="formData.des"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="功能模块" prop="area">
                  <div class="l-rblock" style="padding-right: 64px">
                    <div class="l-rblock">
                      <l-select :options="devList" v-model="formData.area"></l-select>
                    </div>
                    <div class="l-select-btn">
                      <el-button @click="handleClickAreaOpen" size="mini" type="primary">添加</el-button>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="数据库" prop="dbCode">
                  <div class="l-rblock" style="padding-right: 64px">
                    <div class="l-rblock">
                      <el-select v-model="formData.dbCode" filterable placeholder="请选择">
                        <el-option-group v-for="group in lr_dblinkTree" :key="group.id" :label="group.label">
                          <el-option v-for="item in group.children" :key="item.id" :label="item.label" :value="item.id">
                          </el-option>
                        </el-option-group>
                      </el-select>
                    </div>
                    <div class="l-select-btn">
                      <el-button @click="handleClickDbOpen" size="mini" type="primary">添加</el-button>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <div class="l-title">添加数据库表（请先选择数据库）</div>
              </el-col>
              <el-col :span="24">
                <l-edit-table
                  addBtnText="添加数据库表"
                  :dataSource="dbTableData"
                  @addRow="addRow"
                  @deleteRow="deleteRow"
                  @rowClick="rowClick"
                  highlight-current-row
                >
                  <el-table-column prop="type" label="类别" width="56" align="center">
                    <template slot-scope="scope">
                      <el-tag v-if="scope.row.type == 'main'" size="mini">主表</el-tag>
                      <el-tag
                        @click="chlidTagClick(scope.row)"
                        v-else
                        size="mini"
                        style="cursor: pointer"
                        type="warning"
                        >子表</el-tag
                      >
                    </template>
                  </el-table-column>
                  <el-table-column prop="name" label="表名" minWidth="100"> </el-table-column>
                  <el-table-column prop="field" label="外键" minWidth="100">
                    <template v-if="scope.row.type != 'main'" slot-scope="scope">
                      <el-select size="mini" v-model="scope.row.field" placeholder="请选择">
                        <el-option
                          v-for="item in scope.row.columns || []"
                          :key="item.name"
                          :label="item.name"
                          :value="item.name"
                        >
                        </el-option>
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column prop="relationName" label="关联表" minWidth="100">
                    <template v-if="scope.row.type != 'main'" slot-scope="scope">
                      <el-select size="mini" v-model="scope.row.relationName" placeholder="请选择">
                        <el-option
                          v-for="item in relationTables(scope.row.name)"
                          :key="item.name"
                          :label="item.name"
                          :value="item.name"
                        >
                        </el-option>
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column prop="relationField" label="关联主键" minWidth="100">
                    <template v-if="scope.row.type != 'main' && scope.row.relationName" slot-scope="scope">
                      <el-select size="mini" v-model="scope.row.relationField" placeholder="请选择">
                        <el-option
                          v-for="item in relationTableFields(scope.row.relationName)"
                          :key="item.name"
                          :label="item.name"
                          :value="item.name"
                        >
                        </el-option>
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column prop="relationType" label="对应关系" width="100">
                    <template v-if="scope.row.type != 'main' && scope.row.relationName" slot-scope="scope">
                      <el-select
                        size="mini"
                        @change="handleRelationTypeChange(scope.row, $event)"
                        v-model="scope.row.relationType"
                        placeholder="请选择"
                      >
                        <el-option
                          v-for="item in [
                            { id: '1', name: '一对一' },
                            { id: '2', name: '多对一' },
                          ]"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"
                        >
                        </el-option>
                      </el-select>
                    </template>
                  </el-table-column>
                </l-edit-table>
              </el-col>
            </el-form>
          </div>
        </l-panel>
      </template>
      <l-panel
        :title="`${$t('数据表列信息')}${mySelectTableName ? '-' + mySelectTableName : ''}`"
        style="padding: 0; padding-right: 8px"
      >
        <l-table :columns="myColumns" :dataSource="myFileds">
          <template v-slot:isCodeRule="scope">
            <el-switch
              v-if="scope.row.csType == 'string' && !scope.row.isPrimary"
              size="mini"
              v-model="scope.row.isCodeRule"
            >
            </el-switch>
            <div v-else></div>
          </template>

          <template v-slot:dataType="scope">
            <l-select
              :clearable="false"
              v-if="['DateTime', 'string'].includes(scope.row.csType) && !scope.row.isPrimary"
              size="mini"
              v-model="scope.row.dataType"
              :options="getDataTypes(scope.row.csType)"
              placeholder="请选择"
            />
            <div v-else></div>
          </template>

          <template v-slot:queryType="scope">
            <l-select
              :clearable="false"
              v-if="scope.row.csType == 'string' && !scope.row.isPrimary"
              size="mini"
              v-model="scope.row.queryType"
              :options="[
                { value: '1', label: '模糊' },
                { value: '2', label: '准确' },
              ]"
              placeholder="请选择"
            />
            <div v-else></div>
          </template>
        </l-table>
      </l-panel>
    </l-layout>
    <l-layout v-show="steps(1)" :left="320">
      <template #left>
        <l-panel :title="$t('代码结构')" style="padding: 0; padding-left: 8px">
          <el-tree
            ref="tree"
            node-key="id"
            :highlight-current="true"
            :data="codePathTree"
            default-expand-all
            show-checkbox
            :default-checked-keys="[1, 2, 3]"
            @node-click="handleNodeClick"
          >
            <span class="lr-tree-node" slot-scope="{ node }">
              {{ node.label }}
            </span>
          </el-tree>
        </l-panel>
      </template>
      <l-panel style="padding: 0; padding-right: 8px" :title="codePathTtile">
        <l-code-mirror :readOnly="true" :value="codeContent" mode="text/x-csharp"></l-code-mirror>
      </l-panel>
    </l-layout>

    <template #bottom>
      <l-panel style="padding-top: 0">
        <div class="btns">
          <el-button @click="prev" size="mini" :disabled="stepPrevBtn">{{ $t("上一步") }}</el-button>
          <el-button @click="next" size="mini" :disabled="stepNextBtn" :loading="nextBtnLoading">{{
            $t("下一步")
          }}</el-button>
          <el-button @click="handleOk" size="mini" type="primary" :disabled="stepSaveBtn">{{
            $t("生成代码")
          }}</el-button>
        </div>
      </l-panel>
    </template>

    <!--数据库管理-->
    <l-drawer
      :title="$t('数据库管理')"
      :visible.sync="dbManagerVisible"
      :showOk="false"
      :showClose="false"
      size="800px"
    >
      <dblink-index></dblink-index>
    </l-drawer>
    <!--输出区域-->
    <l-drawer
      :title="$t('功能模块管理')"
      :visible.sync="areaManagerVisible"
      :showOk="false"
      :showClose="false"
      size="800px"
      @closed="areaManagerClosed"
    >
      <area-index></area-index>
    </l-drawer>

    <!--数据表添加-->
    <l-codetable-selectdialog
      :visible.sync="dbtableSelectdialog"
      :dbCode="formData.dbCode"
      :isOkClose="false"
      @select="dbSelect"
    >
    </l-codetable-selectdialog>
  </l-layout>
</template>
<script>
import AreaIndex from "../area/index.vue";
import DblinkIndex from "../../../../core/modules/data/views/dblink/index.vue";

const apiCodeTable = window.$api.data.codeTable;
const apiProject = window.$api.codetool.project;

import { generatorEntity } from "../../generator/generatorEntity";
import { generatorDto } from "../../generator/generatorDto";
import { generatorService } from "../../generator/generatorService";
import { generatorBll } from "../../generator/generatorBll";
import { generatorIBll } from "../../generator/generatorIBll";
import { generatorApi } from "../../generator/generatorApi";

import pathTree from "./pathTree";
export default {
  components: {
    AreaIndex,
    DblinkIndex,
  },
  data() {
    return {
      lr_isPage: true,
      stepActive: 0,
      stepPrevBtn: true,
      stepNextBtn: false,
      stepSaveBtn: true,
      nextBtnLoading: false,

      formData: {
        name: "",
        des: "",
        area: "",
        dbCode: "",
      },
      rules: {
        name: [
          { required: true, message: "请输入功能名称", trigger: "blur" },
          { pattern: /^[A-Za-z0-9_]+$/, message: "请输入英文数字或_" },
        ],
        des: [{ required: true, message: "请输入功能描述", trigger: "blur" }],
        area: [{ required: true, message: "请选择功能模块" }],
        dbCode: [{ required: true, message: "请选择数据库", trigger: "change" }],
      },
      dbTableData: [],
      dbtableSelectdialog: false,
      tableColumns: {},
      selectTable: "",
      myColumns: [
        { prop: "name", label: "名称", minWidth: 120 },
        { prop: "coment", label: "备注", minWidth: 120 },
        { prop: "queryType", label: "查询方式", width: 88, align: "center" },
        { prop: "dataType", label: "数据值", width: 120, align: "center" },
        //{prop:'isCodeRule',label:'单据编码',width:80,align:'center'}
      ],

      areaManagerVisible: false,
      devList: [],

      dbManagerVisible: false,

      codePathTree: [],
      code: {},
      codeSelected: "",
    };
  },
  computed: {
    mySelectTableName() {
      if (this.dbTableData.length == 0) {
        return "";
      }
      const tableName = this.selectTable;
      if (this.$validatenull(tableName)) {
        return this.dbTableData.find((t) => t.type == "main").name;
      } else {
        return tableName;
      }
    },
    myFileds() {
      if (this.$validatenull(this.mySelectTableName)) {
        return [];
      } else {
        return this.dbTableData.find((t) => t.name == this.mySelectTableName).columns;
      }
    },
    codePathTtile() {
      if (!this.$validatenull(this.codeSelected) && !this.$validatenull(this.code[this.codeSelected])) {
        return this.code[this.codeSelected].path;
      } else {
        return "请选择预览代码";
      }
    },
    codeContent() {
      let res = "";
      if (this.codeSelected) {
        const code = this.code[this.codeSelected];
        if (code) {
          res = code.content;
        }
      }
      return res;
    },
  },
  created() {
    this.initData();
  },
  methods: {
    initData() {
      this.lr_loadDblink();
      this.getAreas();
    },
    steps(num) {
      return this.stepActive == num;
    },
    prev() {
      if (this.stepActive > 0) {
        this.stepActive--;
      }
      this.$nextTick(() => {
        this.updateBtnState();
      });
    },
    async next() {
      if (await this.myValidateSteps()) {
        if (this.stepActive < 1) {
          this.stepActive++;
        }
        this.$nextTick(() => {
          this.updateBtnState();
        });
      }
    },
    async validateSteps(stepActive) {
      if (this.$validatenull(this.project.f_WebApi)) {
        this.$message({
          type: "error",
          message: "请在项目中设置后端项目地址!",
        });
        return false;
      }

      if (stepActive != 0) {
        return true;
      }

      if (!(await this.$formValidateWraper(this.$refs.baseInfo))) {
        return false;
      }

      if (this.dbTableData.length > 0) {
        if (
          this.dbTableData.find(
            (t) =>
              t.type != "main" &&
              (this.$validatenull(t.field) || this.$validatenull(t.relationName) || this.$validatenull(t.relationField))
          ) != undefined
        ) {
          this.$message({
            type: "error",
            message: "请完善子表信息!",
          });
          return false;
        }

        for (let table of this.dbTableData) {
          if (table.columns.findIndex((t) => t.isPrimary) == -1) {
            this.$message({
              type: "error",
              message: `表【${table.name}】没有主键无法生成!`,
            });
            return false;
          }
        }
      } else {
        this.$message({
          type: "error",
          message: "请添加数据库表!",
        });
        return false;
      }

      await this.generatorCode();

      return true;
    },
    async myValidateSteps() {
      this.nextBtnLoading = true;
      if (this.validateSteps) {
        const res = await this.validateSteps(this.stepActive);
        this.nextBtnLoading = false;
        return res;
      }
      this.nextBtnLoading = false;
      return true;
    },
    updateBtnState() {
      this.stepSaveBtn = true;
      this.stepNextBtn = true;
      this.stepPrevBtn = true;
      switch (this.stepActive) {
        case 0:
          this.stepNextBtn = false;
          break;
        case 1:
          this.stepPrevBtn = false;
          this.stepSaveBtn = false;
          break;
        default:
          this.stepPrevBtn = false;
          this.stepNextBtn = false;
          break;
      }
    },
    async handleOk() {
      if (this.appConfig.online) {
        this.$message({
          type: "warning",
          message: "体验版本无法生成代码文件",
        });
      } else {
        // 生成代码文件
        const loading = this.$loading({
          lock: true,
          text: "代码生成中",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });
        let scode = this.getCode();

        const res = await apiProject.generatorApiCode(scode);
        this.downloadFile(res);

        this.$message({
          type: "success",
          message: "代码生成成功",
        });

        loading.close();
      }
    },
    addRow() {
      if (this.formData.dbCode) {
        this.dbtableSelectdialog = true;
      } else {
        this.$message({
          message: "请选择数据库",
          type: "warning",
        });
      }
    },
    deleteRow(data) {
      this.dbTableData
        .filter((t) => t.relationName == data.row.name)
        .forEach((table) => {
          table.relationName = "";
        });
      this.dbTableData.splice(data.index, 1);
      if (data.row.type == "main" && this.dbTableData.length > 0) {
        this.$set(this.dbTableData[0], "type", "main");
      }
    },
    rowClick(row) {
      this.selectTable = row.name;
    },
    chlidTagClick(row) {
      this.dbTableData.find((t) => {
        return t.type == "main";
      }).type = "chlid";
      row.type = "main";
      row.relationType = "";
      this.$set(this.dbTableData, 0, this.dbTableData[0]);
    },
    relationTables(myName) {
      let list = [];
      this.dbTableData.forEach((item) => {
        if (item.name != myName && item.relationType != "2") {
          list.push(item);
        }
      });
      return list;
    },
    relationTableFields(tableName) {
      let table =
        this.dbTableData.find((t) => {
          return t.name == tableName;
        }) || {};
      return (table.columns || []).filter((t) => t.csType == "string"); // 关联键只能是字串类型
    },
    handleRelationTypeChange({ name }, val) {
      if (val == "2") {
        this.dbTableData.forEach((row) => {
          if (name == row.relationName) {
            row.relationName = "";
          }
        });
      }
    },
    async dbSelect(list, showLoading, hideLoading) {
      showLoading("加载数据表中...");
      const tableList = [];
      const notAddTable = [];
      list.forEach((item) => {
        const table = {
          id: item.f_TableName,
          className: item.f_ClassName,
          name: item.f_TableName,
          comment: item.f_Description,
        };
        // 加载表的列信息
        if (this.tableColumns[table.name]) {
          table.columns = this.tableColumns[table.name];
        } else {
          table.columns = [];
          tableList.push(table);
        }

        if (this.dbTableData.length == 0) {
          table.type = "main";
          table.relationType = "";
          this.dbTableData.push(table);
        } else if (
          this.dbTableData.find((t) => {
            return t.name == table.name;
          }) == undefined
        ) {
          table.type = "chlid";
          table.relationType = "2";
          this.dbTableData.push(table);
        } else {
          notAddTable.push(table.name);
        }
      });

      if (tableList.length > 0) {
        const codeTables = await this.$awaitWraper(
          apiCodeTable.getList(this.formData.dbCode, String(tableList.map((t) => t.name)))
        );
        for (const tableItem of tableList) {
          const codeTable = codeTables.find((t) => t.lr_db_codetableEntity.f_TableName == tableItem.name);
          this.$set(
            tableItem,
            "columns",
            codeTable.lr_db_codecolumnsList.map((t) => ({
              name: t.f_DbColumnName,
              csType: t.f_CsType,
              isIdentity: t.f_IsIdentity == 1,
              isPrimary: t.f_IsPrimaryKey == 1,
              isNullable: t.f_IsNullable == 1,
              coment: t.f_Description,
              isCodeRule: false,
              queryType: t.f_CsType == "string" ? "1" : "2", // 0 没有 1 模糊 2准确 3 范围（时间）
            }))
          );
        }
      }

      if (notAddTable.length > 0) {
        this.$message({
          message: `重复添加表【${String(notAddTable)}】`,
          type: "warning",
        });
      }

      this.dbtableSelectdialog = false;

      hideLoading();
    },

    // 代码生成
    getSetting() {
      // 获取配置信息
      const setting = {
        name: this.formData.name,
        des: this.formData.des,
        dbCode: this.formData.dbCode,
        moduleName: this.devList.find((t) => t.value == this.formData.area).label,
        moduleId: this.formData.area,
        dbTable: this.$deepClone(this.dbTableData),
        userInfo: this.loginInfo,
        project: this.project,
        createTime: this.$getDayTime(),
        company: this.appConfig.company,
        namespace: {
          entity: `${this.formData.area}.ibll`,
          ibll: `${this.formData.area}.ibll`,
          dto: `${this.formData.area}.ibll`,
          bll: `${this.formData.area}.bll`,
          service: `${this.formData.area}.bll`,
          webapi: `${this.formData.area}.controllers`,
        },
        path: {
          entity: `${this.project.f_WebApi}/modules/${this.$lowerFirst(this.formData.area)}/${this.$lowerFirst(
            this.formData.area
          )}.ibll/${this.$upFirst(this.formData.name)}`,
          service: `${this.project.f_WebApi}/modules/${this.$lowerFirst(this.formData.area)}/${this.$lowerFirst(
            this.formData.area
          )}.bll/${this.$upFirst(this.formData.name)}`,
          bll: `${this.project.f_WebApi}/modules/${this.$lowerFirst(this.formData.area)}/${this.$lowerFirst(
            this.formData.area
          )}.bll/${this.$upFirst(this.formData.name)}`,
          ibll: `${this.project.f_WebApi}/modules/${this.$lowerFirst(this.formData.area)}/${this.$lowerFirst(
            this.formData.area
          )}.ibll/${this.$upFirst(this.formData.name)}`,
          webapi: `${this.project.f_WebApi}/modules/${this.$lowerFirst(this.formData.area)}/${this.$lowerFirst(
            this.formData.area
          )}.controllers/${this.$upFirst(this.formData.name)}`,
        },
        apiCodeTree: this.$deepClone(pathTree),
        qTables: [],
      };
      return setting;
    },
    async generatorCode() {
      this.code = {};
      const setting = this.getSetting();

      // 代码生成部分
      // 主表实体生成
      const mainTable = setting.dbTable.find((t) => t.type == "main");
      const entitys = setting.apiCodeTree[0].children[0].children;
      const mainEntityName = `${mainTable.className}Entity.cs`;
      entitys.push({
        id: mainEntityName,
        label: this.$upFirst(mainEntityName),
      });

      setting.entitys = {
        main: {
          table: mainTable,
          name: mainEntityName,
        },
        chlidTables: [],
      };

      // 获取实体模版
      let tempEntity = await this.$awaitWraper(apiProject.getCodeTemp(`entity.cs`));
      this.code[mainEntityName] = {
        path: `${setting.path.entity}/${this.$upFirst(mainEntityName)}`,
        content: generatorEntity(setting, tempEntity, mainTable),
      };
      // 子表实体生成
      let chlidTables = setting.dbTable.filter((t) => t.type != "main");
      chlidTables.forEach((table) => {
        let entityName = `${table.className}Entity.cs`;
        entitys.push({
          id: entityName,
          label: this.$upFirst(entityName),
        });
        setting.entitys.chlidTables.push({
          table: table,
          name: entityName,
        });

        this.code[entityName] = {
          path: `${setting.path.entity}/${this.$upFirst(entityName)}`,
          content: generatorEntity(setting, tempEntity, table),
        };
      });

      // Dto
      if (setting.dbTable.length > 1) {
        entitys.push({
          id: "dto",
          label: `${this.$upFirst(setting.name)}Dto.cs`,
        });

        let tempDto = await this.$awaitWraper(apiProject.getCodeTemp(`dto.cs`));

        this.code.dto = {
          path: `${setting.path.entity}/${this.$upFirst(setting.name)}Dto.cs`,
          content: generatorDto(setting, tempDto),
        };
      }

      // 服务类
      const services = setting.apiCodeTree[1].children[0].children;
      const mainServiceName = `${mainTable.className}Service.cs`;
      services.push({
        id: mainServiceName,
        label: this.$upFirst(mainServiceName),
      });

      let tempService = await this.$awaitWraper(apiProject.getCodeTemp(`service.cs`));
      this.code[mainServiceName] = {
        path: `${setting.path.service}/${this.$upFirst(mainServiceName)}`,
        content: generatorService(setting, tempService, mainTable),
      };

      // 子表服务类生成
      chlidTables.forEach((table) => {
        let serviceName = `${table.className}Service.cs`;
        services.push({
          id: serviceName,
          label: this.$upFirst(serviceName),
        });

        this.code[serviceName] = {
          path: `${setting.path.service}/${this.$upFirst(serviceName)}`,
          content: generatorService(setting, tempService, table),
        };
      });

      // bll层生成
      const blls = setting.apiCodeTree[1].children[1].children;
      const mainBllName = `${mainTable.className}BLL.cs`;
      blls.push({
        id: mainBllName,
        label: this.$upFirst(mainBllName),
      });
      let tempBll = await this.$awaitWraper(apiProject.getCodeTemp(`bll.cs`));
      this.code[mainBllName] = {
        path: `${setting.path.bll}/${this.$upFirst(mainBllName)}`,
        content: generatorBll(setting, tempBll, mainTable),
      };

      chlidTables.forEach((table) => {
        let bllName = `${table.className}BLL.cs`;
        blls.push({
          id: bllName,
          label: this.$upFirst(bllName),
        });

        this.code[bllName] = {
          path: `${setting.path.bll}/${this.$upFirst(bllName)}`,
          content: generatorBll(setting, tempBll, table),
        };
      });

      // ibll
      const iblls = setting.apiCodeTree[0].children[1].children;
      const mainIBllName = `I${mainTable.className}BLL.cs`;
      iblls.push({
        id: mainIBllName,
        label: this.$upFirst(mainIBllName),
      });
      let tempIBll = await this.$awaitWraper(apiProject.getCodeTemp(`ibll.cs`));
      this.code[mainIBllName] = {
        path: `${setting.path.ibll}/${this.$upFirst(mainIBllName)}`,
        content: generatorIBll(setting, tempIBll, mainTable),
      };

      chlidTables.forEach((table) => {
        let ibllName = `I${table.className}BLL.cs`;
        iblls.push({
          id: ibllName,
          label: this.$upFirst(ibllName),
        });

        this.code[ibllName] = {
          path: `${setting.path.ibll}/${this.$upFirst(ibllName)}`,
          content: generatorIBll(setting, tempIBll, table),
        };
      });

      // 控制器
      setting.apiCodeTree[2].children[0].label = `${this.$upFirst(setting.name)}Controller.cs`;
      let tempApi = await this.$awaitWraper(apiProject.getCodeTemp(`api.cs`));
      this.code.api = {
        path: `${setting.path.webapi}/${this.$upFirst(setting.name)}Controller.cs`,
        content: generatorApi(setting, tempApi),
      };

      // 生成完毕
      this.codeSelected = "";
      this.$nextTick(() => {
        this.codeSelected = mainEntityName;
      });
      this.codePathTree = setting.apiCodeTree;

      console.log(setting, this.code, this.appConfig);
    },
    getCode() {
      const checkeds = this.$refs.tree.getCheckedKeys();
      const list = [];
      for (let id in this.code) {
        if (checkeds.indexOf(id) != -1) {
          list.push(this.code[id]);
        }
      }

      const res = {
        list,
        module: this.formData.area,
        moduleName: this.devList.find((t) => t.value == this.formData.area).label,
        modulePath: `${this.project.f_WebApi}/modules/${this.$lowerFirst(this.formData.area)}`,
      };

      return res;
    },

    // 代码预览
    handleNodeClick(node) {
      if (this.code[node.id]) {
        this.codeSelected = node.id;
      }
    },

    // 功能模块
    handleClickAreaOpen() {
      this.areaManagerVisible = true;
    },
    areaManagerClosed() {
      this.getAreas();
    },
    async getAreas() {
      const data = await this.$awaitWraper(window.$api.codetool.area.getList());
      this.devList = (data || []).map((t) => {
        return { label: t.f_Label, value: t.f_Value };
      });
    },
    // 数据库链接
    handleClickDbOpen() {
      this.dbManagerVisible = true;
    },

    getDataTypes(csType) {
      if (csType == "string") {
        return [
          { value: "createId", label: "创建人Id" },
          { value: "createName", label: "创建人名称" },
          { value: "modifyId", label: "编辑人Id" },
          { value: "modifyName", label: "编辑人名称" },
          { value: "code", label: "单据编码" },
        ];
      } else if (csType == "DateTime") {
        return [
          { value: "createTime", label: "创建时间" },
          { value: "modifyTime", label: "编辑时间" },
        ];
      }
    },
    downloadFile(file) {
      let blob = new Blob([file.data], { type: "application/zip" });
      let url = window.URL.createObjectURL(blob);
      let ele = document.createElement("a");
      ele.style.display = "none";
      ele.href = url;
      ele.download = `后端生成_${new Date().getTime()}`;
      document.body.appendChild(ele);
      ele.click();
      ele.remove();
      window.URL.revokeObjectURL(url);
    },
  },
};
</script>
<style lang="scss">
.apicode {
  .title {
    box-sizing: border-box;
    position: absolute;
    top: 0;
    left: 16px;
    height: 100%;
    display: flex;
    align-items: center;
  }
  .steps {
    position: relative;
    margin: auto;
    height: 100%;
    width: 480px;
    text-align: center;

    .el-steps--simple {
      background: none;
      padding: 14px 8%;
    }
  }
  .btns {
    position: absolute;
    right: 0;
    top: 0;
    height: 100%;
    padding-right: 8px;
    display: flex;
    align-items: center;
  }
  .base-form-wraper {
    padding: 16px;
  }
  .l-select-btn {
    position: absolute;
    right: 0;
    top: 0;
    box-sizing: border-box;
  }
}
</style>
